package com.gitee.wsl.compose.ext.text

import androidx.compose.ui.text.TextRange
import com.gitee.wsl.platform.Platform


private fun Int.coerceStartOfParagraph(text: String): Int {
    val previousNewLineCharacterIndex = text.substring(0, this)
        .lastIndexOf(Platform.fileSeparator)

    if (previousNewLineCharacterIndex == -1) {
        return 0
    }

    return previousNewLineCharacterIndex + Platform.fileSeparator.length
}

private fun Int.coerceEndOfParagraph(text: String): Int {
    val nextNewLineCharacterIndex = text.substring(this)
        .indexOf(Platform.fileSeparator)

    if (nextNewLineCharacterIndex == -1) {
        return text.length
    }

    return this + nextNewLineCharacterIndex + 1
}

fun TextRange.coerceParagraph(text: String) = TextRange(
    start = start.coerceStartOfParagraph(text),
    end = end.coerceEndOfParagraph(text)
)

fun TextRange.coerceNotReversed() = if (start < end) {
    this
} else {
    TextRange(end, start)
}